<?php

function MODULE_HOOK($moduleName, $hookFunction, $parameterArray=array()) {
    if (file_exists(DOCUMENT_ROOT . '/application/Modules/' . $moduleName . '/' . $moduleName . '.php')) {
        include_once(DOCUMENT_ROOT . '/application/Modules/' . $moduleName . '/' . $moduleName . '.php');
        return $moduleName::$hookFunction($parameterArray);
    }
}

function is_valid_mobile_fr($input) {
    $valid = false;
    $portable = $output = preg_replace('/[^0-9]/', '', $input);
    if (strlen($portable) == 10 && (substr($portable, 0, 2) == '06' || substr($portable, 0, 2) == '07')) {
        $valid = true;
    }
    return $valid;
}


function is_valid_phone($input) {
    $valid = false;
    $portable = $output = preg_replace('/[^0-9]/', '', $input);
    if (strlen($portable) == 10 && (substr($portable, 0, 1) == '0')) {
        $valid = true;
    }
    return $valid;
}

function random_color() {
    $r = str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT);
    $g = str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT);
    $b = str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT);
    return $r . $g . $b;
}

function array_copy($arr) {
    $newArray = array();
    foreach ($arr as $key => $value) {
        if (is_array($value))
            $newArray[$key] = array_copy($value);
        elseif (is_object($value))
            $newArray[$key] = clone $value;
        else
            $newArray[$key] = $value;
    }
    return $newArray;
}

function array_filter_numeric($input) {
    $result = array();
    if (is_array($input)) {
        foreach ($input as $key => $value) {
            if (is_numeric($value)) {
                $result[$key] = $value;
            }
        }
    }
    return $result;
}

function find_serie_deletion_starter($input) {
    $minor = -1;
    if (is_array($input)) {
        foreach ($input as $key => $value) {
            if ($value == 'n') {
                $minor = ($minor == -1 || $minor > $input[$key - 1]) ? $input[$key - 1] : $minor;
            }
        }
    }
    return $minor;
}

function filter_array($input) {
    if (is_array($input)) {
        foreach ($input as $key => $link) {
            if ($input[$key] == '') {
                unset($input[$key]);
            }
        }
    }
    return $input;
}

function get_real_ip() {
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                    return $ip;
                }
            }
        }
    }
}

function time_to_euro_date($input) {
    return date('d/m/Y', $input);
}

function time_to_hybrid_date($input) {
    return date('d-m-Y', $input);
}

function date_euro_to_unix_format($input) {
    // Assuming 6/12/2012 => 6-12-2012
    $date_array = explode('/', $input);
    return (is_array($date_array) && count($date_array) == 3) ? $date_array[0] . '-' . $date_array[1] . '-' . $date_array[2] : '1-1-1970';
}

function date_euro_to_time($input) {
    // Assuming 6/12/2012 => 6-12-2012
    $date_array = explode('/', $input);
    $timestamp = (is_array($date_array) && count($date_array) == 3) ? $date_array[0] . '-' . $date_array[1] . '-' . $date_array[2] : '1-1-1970';
    return strtotime($timestamp);
}

function ajax_sanitize_input_for_db_insert($input) {
    if (is_string($input)) {
        return '"' . addslashes($input) . '"';
    }
    $resultArray = array();
    foreach ($input as $item) {
        $resultArray[] = '"' . addslashes($item) . '"';
    }
    return $resultArray;
}

function hour_str_to_time($input) {
    $time = 0;
    $data = explode('h', str_replace(' ', '', $input));
    if (is_array($data) && count($data) == 2) {
        $time = $data[0] * 3600 + $data[1] * 60;
    }
    return $time;
}

function pad2($input) {
    return ($input < 10) ? '0' . $input : $input;
}

function minutes_to_str_hour($input) {
    $hours = (int) ($input / 60);
    $minutes = (int) (($input - (60 * $hours)));
    return ($hours > 0) ? $hours . 'h' . pad2($minutes) . ' min' : pad2($minutes) . ' min';
}

function time_to_str_hour($input) {
    $hours = (int) ($input / 3600);
    $minutes = (int) (($input - (3600 * $hours)) / 60);
    return ($hours > 0) ? pad2($hours) . 'h' . pad2($minutes) : pad2($minutes) . 'min';
}

function time_to_str_duration($input) {
    $hours = (int) ($input / 3600);
    $minutes = (int) (($input - (3600 * $hours)) / 60);
    return ($hours > 0) ? $hours . 'h' . pad2($minutes) : $minutes . 'min';
}

function is_valid_md5($md5) {
    return preg_match("#^[0-9a-f]{32}$#i", $md5);
}

function image_path($image) {
    return config_get('public_images') . '/' . $image;
}

function stripslashes_recursive($var) {
    return (is_array($var) ? array_map('stripslashes_recursive', $var) : stripslashes($var));
}

function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float) $usec + (float) $sec);
}

function transform_path($input) {
    if (strpos($input, '/') !== FALSE) {
        if (strpos($input, '\\') !== FALSE && strpos($input, '/') < strpos($input, '\\')) {
            $input = str_replace('\\', '/', $input);
        }
    }
    return $input;
}

function object_to_array($d) {
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
        $d = get_object_vars($d);
    }
    if (is_array($d)) {
        /*
         * Return array converted to object
         * Using __FUNCTION__ (Magic constant)
         * for recursive call
         */
        return array_map(__FUNCTION__, $d);
    } else {
        // Return array
        return $d;
    }
}

function tpl_get_full_path($filename) {
    $input = $filename;
    $output = str_replace('.phtml', '', $input);

    $folders = '';
    if (strstr($output, '_') !== false) {
        $folder_array = explode('_', $output);
        for ($i = 0; $i < count($folder_array) - 1; $i++) {
            $folders .= $folder_array[$i] . '/';
        }
    }

    return $folders . $filename;
}

/**
 * str_lreplace() - Replaces last occurence of a string in another string
 * @param type $search
 * @param type $replace
 * @param type $subject
 * @return type 
 */
function str_lreplace($search, $replace, $subject) {
    $pos = strrpos($subject, $search);

    if ($pos !== false) {
        $subject = substr_replace($subject, $replace, $pos, strlen($search));
    }

    return $subject;
}

/**
 * strip_accents() - Remove accents
 *
 * @param mixed $texte
 * @return
 */
function strip_accents($texte) {
    $texte = str_replace(
            array(
        'à', 'â', 'ä', 'á', 'ã', 'å',
        'î', 'ï', 'ì', 'í',
        'ô', 'ö', 'ò', 'ó', 'õ', 'ø',
        'ù', 'û', 'ü', 'ú',
        'é', 'è', 'ê', 'ë',
        'ç', 'ÿ', 'ñ',
        'À', 'Â', 'Ä', '�?', 'Ã', 'Å',
        'Î', '�?', 'Ì', '�?',
        'Ô', 'Ö', 'Ò', 'Ó', 'Õ', 'Ø',
        'Ù', 'Û', 'Ü', 'Ú',
        'É', 'È', 'Ê', 'Ë',
        'Ç', 'Ÿ', 'Ñ'
            ), array(
        'a', 'a', 'a', 'a', 'a', 'a',
        'i', 'i', 'i', 'i',
        'o', 'o', 'o', 'o', 'o', 'o',
        'u', 'u', 'u', 'u',
        'e', 'e', 'e', 'e',
        'c', 'y', 'n',
        'A', 'A', 'A', 'A', 'A', 'A',
        'I', 'I', 'I', 'I',
        'O', 'O', 'O', 'O', 'O', 'O',
        'U', 'U', 'U', 'U',
        'E', 'E', 'E', 'E',
        'C', 'Y', 'N'
            ), $texte);
    return $texte;
}

/**
 * get_file_ext() - Return file extension
 *
 * @param mixed $file
 * @return
 */
function get_file_ext($file) {
    $path_parts = pathinfo($file);
    return isset($path_parts['extension']) ? $path_parts['extension'] : '';
}

function base64_url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64_url_decode($data) {
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}

function __crypt($data) {
    $key = config_get('security_string');
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $data, MCRYPT_MODE_CBC, md5(md5($key))));
}

function __decrypt($data) {
    $key = config_get('security_string');
    return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($data), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
}

function strstrarr($haystack, $needle_arr) {
    if (!is_array($needle_arr)) {
        return strstr($haystack, $needle_arr);
    }
    foreach ($needle_arr as $needle) {
        if (strstr($haystack, $needle)) {
            return TRUE;
        }
    }
    return FALSE;
}

function stristrarr($haystack, $needle_arr) {
    if (!is_array($needle_arr)) {
        return stristr($haystack, $needle_arr);
    }
    foreach ($needle_arr as $needle) {
        if (stristr($haystack, $needle)) {
            return TRUE;
        }
    }
    return FALSE;
}

function in_arrayr($needle, $haystack) {
    foreach ($haystack as $v) {
        if ($needle == $v)
            return true;
        elseif (is_array($v))
            return in_arrayr($needle, $v);
    }
    return false;
}

function array_keysr($input, $search_value = null) {

    $output = ($search_value !== null ? array_keys($input, $search_value) : array_keys($input));
    foreach ($input as $sub) {
        if (is_array($sub)) {
            $output = ($search_value !== null ? array_merge($output, array_keysr($sub, $search_value)) : array_merge($output, array_keysr($sub)));
        }
    }
    return $output;
}

function Zip($source, $destination) {
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }
    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }
    $source = str_replace('\\', '/', realpath($source));
    if (is_dir($source) === true) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
        foreach ($files as $file) {
            $file = str_replace('\\', '/', realpath($file));
            if (is_dir($file) === true) {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            } else if (is_file($file) === true) {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    } else if (is_file($source) === true) {
        $zip->addFromString(basename($source), file_get_contents($source));
    }
    return $zip->close();
}

function Unzip($src_file, $dest_dir) {
    $zip = new ZipArchive;
    if ($zip->open($src_file) === TRUE) {
        $zip->extractTo($dest_dir);
        $zip->close();
    }
}

function file_get_contents_curl($url) {
    $ch = curl_init($url);
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

function post_curl($url, $fields) {
    $fields_string = '';
    $fields_string = http_build_query($fields);
    rtrim($fields_string, '&');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function strip_non_alnum($string) {
    return preg_replace("/[^a-zA-Z0-9]/", "", $string);
}

function br2nl($input) {
    return str_replace(array("<br>", "<br/>"), array("\n", "\n"), $input);
}